package melon.saber.core;

import melon.saber.core.cfg.ContextConfig;
import melon.saber.core.event.Event;
import melon.saber.core.event.EventDispatcher;
import melon.saber.core.event.Subscriber;

import com.google.common.base.Strings;
import com.google.common.eventbus.EventBus;

/**
 * 抽象的上下文
 * @author jin
 *
 */
public abstract class AbstractContext implements Context, EventDispatcher {
	
	private ContextConfig config;
	private volatile EventBus eventBus; //事件总线(全局唯一)
	
	@Override
	public void load() {
		if (eventBus == null) {
			eventBus = new EventBus();
		}
	}
	
	@Override
	public void release() {
		eventBus = null;
	}
	
	@Override
	public void reload() {
		release();
		load();
	}
	
	@Override
	public String getProperty(String key) {
		return Strings.nullToEmpty(config.getProperty(key));
	}
	
	@Override
	public Integer getIntProperty(String key) {
		Integer i = null;
		try {
			i = Integer.valueOf(getProperty(key));
		} catch (NumberFormatException e) {
			i = 0;
		}
		return i;
	}
	
	@Override
	public Long getLongProperty(String key) {
		Long l = null;
		try {
			l = Long.valueOf(getProperty(key));
		} catch (NumberFormatException e) {
			l = 0l;
		}
		return l;
	}
	
	@Override
	public Float getFloatProperty(String key) {
		Float f = null;
		try {
			f = Float.valueOf(getProperty(key));
		} catch (NumberFormatException e) {
			f = 0.0f;
		}
		return f;
	}
	
	@Override
	public Boolean getBooleanProperty(String key) {
		Boolean b = null;
		try {
			b = Boolean.valueOf(getProperty(key));
		} catch (NumberFormatException e) {
			b = false;
		}
		return b;
	}
	
	@Override
	public void setPropertyProperty(String key, String value) {
		config.setProperty(key, value);
	}
	
	/**
	 * 向事件总线派发事件
	 */
	@Override
	public void dispatch(Event event) {
		eventBus.post(event);
	}
	
	public void registerSubscriber(Object subscriber) {
		eventBus.register(subscriber);
	}
	
	/**
	 * 向事件总线注册订阅者
	 * @param subscriber
	 */
	public void registerSubscriber(Subscriber subscriber) {
		eventBus.register(subscriber);
	}
	
}
